import React from 'react';
import _ from 'lodash';
import moment from 'moment';
import { connect } from 'umi';

import TMainBasePage from '@/base/TMainBasePage';

import { TRAlert } from '#/components';
import emitter from '#/utils/events';
import renovate from '#/utils/renovate';

import TabMenu from './components/TabMenu';
import SuperShort from './components/SuperShort';
import styles from './style.less';

@connect(({ global }) => ({
  currentUser: global.configure.currentUser,
  buttonPermissions: global.configure.buttonPermissions,
  menuCode: global.configure.menuCode,
}))
export default class PowerExceed extends TMainBasePage {
  constructor(props) {
    super(props);
    this.state = {
      date: [moment(), moment()],
      signPoint: 'A-1',
      dataSourceList: [],
      dataColumn: [],
    };
    this._settlement_ = {};
    this._isSpinLoading_ = true;
    this.maxinLoading = false;
  }

  beforeunload(e) {
    if (renovate.isRenovate) {
      let confirmationMessage = '当前工作将不被保存，继续执行此操作？';
      (e || window.event).returnValue = confirmationMessage;
      return confirmationMessage;
    }
  }

  componentDidMount() {
    super.componentDidMount();
    emitter.addListener('onChangeMnue', this.__onMnueChange.bind(this));
    this.__beforeunload = this.beforeunload.bind(this);
    window.addEventListener('beforeunload', this.__beforeunload);
  }

  async componentWillUnmount() {
    super.componentWillUnmount();
    this.__beforeunload && window.removeEventListener('beforeunload', this.__beforeunload);
  }
  async componentWillMount() {
    await this._onGetStation(async () => {
      let obj = { index: 1 };
      if (renovate.isRenovate) {
        obj = await TRAlert.show('当前工作将不被保存，继续执行此操作？');
        renovate.isRenovate = false;
      }
      if (obj.index === 1) {
        const { stationList = [] } = this.state;
        this.setState(
          {
            stationList: stationList.map((m) => {
              this._settlement_[m.value] = m.children || [];
              return { lable: m.lable, value: m.value, children: m.children };
            }),
          },
          () => {
            this._isPositionLoading_ = false;
            this.setState({ flag: true });
          },
        );
      }
    }, this.props.menuCode);
  }

  __onMnueChange = async () => {
    if (renovate.isRenovate) {
      await TRAlert.show('当前工作将不被保存，继续执行此操作？');
      renovate.isRenovate = false;
    }
  };

  _onGetStationName(stationList, selectStationList) {
    let keyVal = stationList.filter((item) => item.value === selectStationList[0])[0]?.lable || '';
    var end = selectStationList[selectStationList.length - 1];
    stationList.forEach((item) => {
      if (item.children) {
        item.children.forEach((jitem) => {
          if (end === jitem.stationId) {
            keyVal += '/' + jitem.stationName;
          }
        });
      }
    });
    return keyVal;
  }

  saveValue(obj) {
    const { date } = obj;
    this.setState({
      date: date,
    });
  }

  getClumnData = (clumn, dataSource, signPoint) => {
    const dataColumn = clumn.map((i) => {
      if (i.code === 'typeLink') {
        return false;
      }
      return i.name;
    });
    const dataSourceList = dataSource.map((i) => {
      const dataPoint = i.data.map((item) => {
        return item.value ?? '-';
      });
      return dataPoint;
    });
    this.setState({
      dataSourceList: dataSourceList,
      dataColumn: _.compact(dataColumn),
      signPoint: signPoint,
    });
  };

  contentLoadingFun(maxinLoading) {
    this.setState({ maxinLoading });
  }

  render() {
    const {
      stationList,
      spinLoding,
      errorMsg = '',
      newSelectStationId,
      date,
      dataSourceList,
      dataColumn,
      signPoint,
      maxinLoading,
    } = this.state;
    const { buttonPermissions } = this.props;
    if (this._isSpinLoading_ || spinLoding) {
      return this._onLoadingRender();
    }
    if (stationList.length === 0) {
      return this._onEmptyRender();
    }
    if (errorMsg?.length > 0) {
      return this._onErrorRender();
    }

    return (
      <div className={styles.container}>
        <div className={styles.containerBot}>
          <div className={styles.tool}>
            {this._onStationPowerSelectRender()}
            <TabMenu
              saveValue={this.saveValue.bind(this)}
              selectStationId={Number(newSelectStationId)}
              buttonPermissions={buttonPermissions}
              dataSourceList={dataSourceList}
              dataColumn={dataColumn}
              signPoint={signPoint}
              maxinLoadingFun={this.contentLoadingFun.bind(this)}
            />
          </div>
          <SuperShort
            selectStationId={Number(newSelectStationId)}
            dataTime={date}
            onGetData={this.getClumnData.bind(this)}
            buttonPermissions={buttonPermissions}
            maxinLoading={maxinLoading}
            maxinLoadingFun={this.contentLoadingFun.bind(this)}
          />
        </div>
      </div>
    );
  }
}
